package com.hqyj.ssm_project.controller;

import com.hqyj.ssm_project.pojo.*;
import com.hqyj.ssm_project.service.ApplicationService;
import com.hqyj.ssm_project.service.RoleService;
import com.hqyj.ssm_project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ApplicationController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ApplicationService applicationService;
    //添加请假条--页面
    @RequestMapping("/addApplicationPage.do")
    public String addApplicationPage() {

        return "addApplication";
    }
   //XML解析
    @RequestMapping("/selectNextApprover.do")
    public @ResponseBody
    Map<String, Object> selectNextApprover(HttpServletRequest request, HttpServletResponse response) throws IOException, ParserConfigurationException, SAXException {
        HttpSession session = request.getSession();
        User userSession = (User) session.getAttribute("userSession");
        Integer userId = userSession.getUserId();
        User_Role user_role = roleService.seleteUser_RoleByUserId(userId);
        Role thisRole = roleService.selectByPrimaryKey(user_role.getRoleId());
        String roleName = thisRole.getRoleName();
        List<String> superRoleList = new ArrayList<>();


        //创建一个DocumentBuilderFactory的对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //创建DocumentBuilder对象
        DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
        //通过DocumentBuilder对象的parser方法加载readRole.xml文件到当前项目下
        Document parse = documentBuilder.parse("F:\\ssm_project_git\\ssm_project\\ssm_module\\src\\main\\resources\\readRole.xml");
        //获取所有role节点的集合
        NodeList roleList = parse.getElementsByTagName("role");
        //获取roleList.第0号节点
        Node role = roleList.item(0);
        //遍历子节点
        NodeList childNodes = role.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                //获取了element类型节点的节点名
                String nodeName = childNodes.item(i).getNodeName();
                //获取了element类型节点的节点值
                String nodeValue = childNodes.item(i).getFirstChild().getNodeValue();
                if (nodeValue.equals(roleName) == false) {
                    superRoleList.add(childNodes.item(i).getFirstChild().getNodeValue());
                }
            }
        }
        String superRoleName = "";
        if (roleName.equals("部门经理")) {
            superRoleName = superRoleList.get(0);
            System.out.println("上一级:" + superRoleName);
        } else if (roleName.equals("普通用户")) {
            superRoleName = superRoleList.get(1);
            System.out.println("上一级:" + superRoleName);
        }
        Role superRole = roleService.selectRoleByRoleName(superRoleName);
        List<User> superUserist = userService.selectSuperUser(superRole.getRoleId());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("superUser", superUserist);
        return map;
    }
    //请假条生成--
    @RequestMapping(value = "/addApplication.do", method = RequestMethod.POST)
    public String addApplication(Application application, String applicationStart, String applicationEnd) throws ParseException {
//      applicationStart=applicationStart.substring(0,10)+" "+applicationStart.substring(11,19);//截取方法
        applicationEnd = applicationEnd.replaceAll("T", " ") + ":00";//替换方法
        applicationStart = applicationStart.replaceAll("T", " ") + ":00";//替换方法
        application.setApplicationStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(applicationStart));
        application.setApplicationEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(applicationEnd));
        Date date = new Date();
        application.setApplicationCreateTime(date);
        applicationService.insert(application);
        System.out.println(application);
        //----------
        Approve approve = new Approve();
        approve.setUserId(application.getDetails().getApproveId());
        applicationService.createApprove(approve);
        //----------
        Details details = new Details();
        details.setApplicationId(application.getApplicationId());//获取自增返回的ApplicationId 表Id
        details.setUserId(application.getUserId());//申请人Id
        details.setApproveId(approve.getApproveId());//审批者Id
        details.setDetailsStatus("0");//0未提交
        applicationService.insertDetails(details);
        return "redirect:applicationPageById.do?id=" + application.getUserId();
    }
    //查看当前用户请假列表
    @RequestMapping(value = "/applicationPageById.do", method = RequestMethod.GET)
    public String applicationPageById(ModelMap modelMap, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User userSession = (User) session.getAttribute("userSession");
        Integer userId = userSession.getUserId();

        System.out.println("-------session----" + userSession.toString());
        List<Application> application = applicationService.selectByUserId(userId);
        modelMap.put("applicationList", application);
        return "applicationPage";
    }
    //查看请假条详情
    @RequestMapping(value = "/selectAppdetailById.do", method = RequestMethod.GET)
    public String selectAppdetailById(Integer applicationId, ModelMap modelMap) {
        Application application = applicationService.selectAppdetailById(applicationId);
        modelMap.put("application", application);
        return "applicationDetailPage";
    }
    //请假条提交--ajax
    @RequestMapping(value = "/applicationCommit.do", method = RequestMethod.POST)
    public @ResponseBody
    boolean applicationCommit(Integer applicationId) {
        Date date = new Date();
        Application application = new Application();
        application.setApplicationId(applicationId);
        application.setApplicationCommitTime(date);
        int i = applicationService.updateCommitTime(application);
        Details details = new Details();
        details.setApplicationId(applicationId);
        details.setDetailsStatus("1");
        applicationService.updateStatus(details);
        return true;
    }
    //经理审批--列表
    @RequestMapping(value = "/applicationForApprovePage.do")
    public String applicationForApprovePage(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("userSession");
        Integer userId = user.getUserId();
        //用审批者的userId查询需要审批的请假条
        List<Application> applications = applicationService.selectListToApproveByApproveUserId(userId);
        model.addAttribute("applicationList", applications);
        return "applicationForApprovePage";
    }
   //经理审批--页面
    @RequestMapping(value = "/approveThisApplicationPage.do")
    public String approveThisApplicationPage(Integer approveId, Model model) {
        Approve approve = applicationService.selectApproveByapproveId(approveId);
        model.addAttribute("approve", approve);
        System.out.println(approve.getApproveOpinion());
        return "approveThisApplicationPage";
    }
    //最终审批--列表
    @RequestMapping(value = "/applicationForApproveFinalPage.do")
    public String applicationForApproveFinalPage(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("userSession");
        Integer userId = user.getUserId();
        //用审批者的userId查询需要审批的请假条
        List<Application> applications = applicationService.selectListToApproveByApproveUserId(userId);
        model.addAttribute("applicationList", applications);
        return "applicationForApproveFinalPage";
    }
   //最终审批--页面
    @RequestMapping(value = "/approveThisApplicationFinalPage.do")
    public String approveThisApplicationFinalPage(Integer approveId, Model model) {
        Approve approve = applicationService.selectApproveByapproveId(approveId);
        model.addAttribute("approve", approve);
        System.out.println(approve.getApproveOpinion());
        return "approveThisApplicationFinalPage";
    }
    //驳回 ajax
    @RequestMapping(value = "rejectApplication.do")
    @ResponseBody
    public boolean rejectApplication(Integer approveId) {
        applicationService.rejectApplication(approveId);
        return true;
    }
    //经理审批--提交
    @RequestMapping(value = "/approveApplication.do", method = RequestMethod.POST)
    public String approveApplication(Approve approve) {
        Date date = new Date();
        approve.setApproveTime(date);
        applicationService.approveApplication(approve);
        return "redirect:applicationForApprovePage.do";
    }
    //最终审批---提交
    @RequestMapping(value = "/approveApplicationFinal.do", method = RequestMethod.POST)
    public String approveApplicationFinal(Approve approve) {
        Date date = new Date();
        approve.setApproveTime(date);
        applicationService.approveApplication(approve);
        //修改状态 为已完成
        Details details = new Details();
        details.setDetailsStatus("2");  // 0 未提交  1 审批中  2 审批完成  3 驳回
        details.setApproveId(approve.getApproveId());
        applicationService.updateStatusByApproveId(details);
        return "redirect:applicationForApproveFinalPage.do";
    }

}
